﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Services.Providers;
using System.IO;
using System.Data.Services;
using System.Web.Configuration;
using System.Data.Objects;
using log4net;

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

namespace CalligraphyDataService
{
    /// <summary>
    ///PhotoStreamProvider 的摘要说明
    /// </summary>
    public class PhotoStreamProvider : IDataServiceStreamProvider, IDisposable
    {
        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        CalligraphyEntities _entities;
        T_Photo _cachePhoto;
        string _tempFilePath;

        public PhotoStreamProvider(CalligraphyEntities entities)
        {
            _entities = entities;
            _tempFilePath = GetTempPath();
            log.Info("Creat PhotoStreamProvider Instance");
        }

        public void DeleteStream(object entity, System.Data.Services.DataServiceOperationContext operationContext)
        {
            throw new NotImplementedException();
        }

        public System.IO.Stream GetReadStream(object entity, string etag, bool? checkETagForEquality, System.Data.Services.DataServiceOperationContext operationContext)
        {
            T_Photo photo = entity as T_Photo;
            if (photo != null)
            {
                string photoFullPaht = GetPhotoFullPath(photo);
                log.Info(photoFullPaht);
                try
                {
                    return new FileStream(photoFullPaht, FileMode.Open);

                }
                catch (Exception ep)
                {
                    log.Error("读取图片文件失败,详细信息：" + ep.Message);
                    throw new DataServiceException(500, "The image could not be found." + ep.Message);
                }
            }
            else
            {
                return null;
            }
        }

        private static string GetTempPath()
        {
            return WebConfigurationManager.AppSettings["RubbingPhotoBasePath"] + @"Temp\" + Guid.NewGuid().ToString();
        }

        private static string GetPhotoFullPath(T_Photo p)
        {
            return WebConfigurationManager.AppSettings["RubbingPhotoBasePath"] + p.ID + "." + GetFileExtensionName(p);
        }

        private static string GetFileExtensionName(T_Photo p)
        {
            if (string.IsNullOrEmpty(p.ContentType))
                return string.Empty;
            var strs = p.ContentType.Split('/');
            return strs[1];
        }

        public Uri GetReadStreamUri(object entity, System.Data.Services.DataServiceOperationContext operationContext)
        {
            return null;
        }

        public string GetStreamContentType(object entity, System.Data.Services.DataServiceOperationContext operationContext)
        {
              T_Photo p = entity as T_Photo;
              if (p != null)
              {
                  if(!string.IsNullOrEmpty(p.ContentType))
                      return p.ContentType.Trim();
              }

            throw new DataServiceException(500, "The image could not be found.");
        }

        public string GetStreamETag(object entity, System.Data.Services.DataServiceOperationContext operationContext)
        {
            return null;
        }

        public System.IO.Stream GetWriteStream(object entity, string etag, bool? checkETagForEquality, System.Data.Services.DataServiceOperationContext operationContext)
        {
            try
            {
                T_Photo photo = entity as T_Photo;
                if (operationContext.RequestMethod == "PUT")
                {
                    return new FileStream(GetPhotoFullPath(photo), FileMode.Open, FileAccess.Write);
                }
                //POST的情况
                else
                {
                    photo.ContentType = operationContext.RequestHeaders["Content-Type"];
                    _cachePhoto = photo;                    

                    return new FileStream(_tempFilePath, FileMode.Create);
                }
            }
            catch (Exception ep)
            {
                log.Error("GetWriteStream 里发生错误 " + ep.Message);
            }
            return null;
        }

        public string ResolveType(string entitySetName, System.Data.Services.DataServiceOperationContext operationContext)
        {
            if (entitySetName == "T_Photo")
            {
                return "CalligraphyModel.T_Photo";
            }
            return string.Empty;
        }

        public int StreamBufferSize
        {
            get
            {
                return 6400000;
            }
        }

        public void Dispose()
        {
            log.Info(Environment.UserName);
            if (_cachePhoto != null)
            {
                try
                {                    
                    string _destFilePath = GetPhotoFullPath(_cachePhoto);
                    File.Move(_tempFilePath, _destFilePath);                  
                    
                }
                catch (Exception ep)
                {
                    log.Error("Dispose 里发生错误 " + DateTime.Now.ToShortTimeString() + ep.Message);
                }
            }
        }

    }
}